﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Linq;
using DAL;

namespace BIZ
{
    public class OrderBIZ
    {
        public void Add(Order order)
        {
            WebUtils.db.Orders.InsertOnSubmit(order);
            WebUtils.db.ORDERDETAILs.InsertAllOnSubmit(order.ORDERDETAILs);

            WebUtils.db.SubmitChanges();
        }

        public void Edit(Order order)
        {
            var _order = WebUtils.db.Orders.Single(o => o.OrderID.Equals(order.OrderID));

            _order.CustomerName = order.CustomerName;
            _order.CustomerPhone = order.CustomerPhone;
            _order.CustomerEmail = order.CustomerEmail;
            _order.CustomerAddress = order.CustomerAddress;
            _order.Note = order.Note;

            WebUtils.db.SubmitChanges();
        }

        public Order getId(Guid id)
        {
            var o = (from order in WebUtils.db.Orders
                    where order.OrderID.Equals(id)
                    select order).FirstOrDefault();

            //o.ORDERDETAILs = (from od in WebUtils.db.ORDERDETAILs where od.OrderID.Equals(o.OrderID) select od).;
            o.ORDERDETAILs.Load();

            foreach (var item in o.ORDERDETAILs)
            {
                item.PRODUCT = WebUtils.db.PRODUCTs.SingleOrDefault(p => p.ProductID.Equals(item.ProductID));
            }

            return o;
        }

        public List<Order> GetAll(int status)
        {
            return WebUtils.db.Orders.ToList();
        }

        public List<Order> GetAll(int status, DateTime fromDate, DateTime toDate)
        {
            IQueryable<Order> list;
            if (status == 0)
            {
                list = (from order in WebUtils.db.Orders where order.CreateDate >= fromDate && order.CreateDate <= toDate orderby order.CreateDate select order);
            }
            else
            {
                list = (from order in WebUtils.db.Orders where order.Status == (status==1?true:false) && order.CreateDate >= fromDate && order.CreateDate <= toDate  orderby order.CreateDate select order);
            }

            return list.ToList();
        }

        public void ChangeStatus(Guid id, bool status)
        {
            Order p = WebUtils.db.Orders.Single(order => order.OrderID.Equals(id));
            p.Status = status;

            WebUtils.db.SubmitChanges();
        }
    }
}
